<?php

class Reportes extends Onecore_Controller {

    public function index() {
        $banner["module_name"] = utf8_encode("Inscritos por Grupo");
        $banner["module_description"] = $this->_moduleDescription;
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Reportes";
        $this->layout->view("/reportes/index", $data);
    }

    public function crecimiento_lider() {
        $banner["module_name"] = utf8_encode("Crecimiento de Lideres");
        $banner["module_description"] = $this->_moduleDescription;
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Crecimiento Lider";
        $this->layout->view("/reportes/leader_report", $data);
    }

    public function crecimiento_prop_lider() {
        $banner["module_name"] = $this->_moduleName;
        $banner["module_description"] = $this->_moduleDescription;
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Reporte crecimiento usuario lider";
        
        //OBTENER ID USUARIO POR SESION
        $user_id = 1;
        //OBTENER GRUPO CELULA DONDE ES LIDER
        $group_id = 1;
        
        $ug = $user_id.'_'.$group_id;
        $data["user_data"] = $ug;
        
        $this->layout->view("/reportes/proper_leader_report", $data);

        
    }

    public function userstree() {
        $banner["module_name"] = $this->_moduleName;
        $banner["module_description"] = $this->_moduleDescription;
        $data["module_banner"] = $this->load->view("/include/sections/module_banner/module_title", $banner, true);
        $data["page_title"] = "Árbol de miembros";
        $this->layout->view("/reportes/arbol", $data);
    }

    public function get_registered_people() {
        $report_values = $this->input->post();
        $array_month = array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio',
            'Julio', 'Agosto', 'Septiembre', 'Noviembre', 'Diciembre');
        $array_type = array('INSCRITOS', 'HOMBRES', 'MUJERES', 'LIDERES', 'DISCIPULOS');

        $initial_month = $report_values['mes_id_inic'];
        $final_month = $report_values['mes_id_fin'];

        $this->load->model('tiporols_model');
        $leader_id = $this->tiporols_model->getBynombrerol('lider');
        $leader_id = $leader_id[0]->TipoRolId;
        $disc_id = $this->tiporols_model->getBynombrerol('discipulo');
        $disc_id = $disc_id[0]->TipoRolId;


        $data = array();
        $this->load->model("grupos_model");
        $categories = array();

        for ($i = $initial_month; $i <= $final_month; $i++) {
            if (!empty($array_month[$i - 1]))
                $categories[] = $array_month[$i - 1];
        }

        foreach ($array_type as $at) {
            $data_array = array();
            $j = 0;
            for ($i = $initial_month; $i <= $final_month; $i++) {
                $data_array[$j] = $this->grupos_model->get_total_persons($report_values['TipoGrupoId'], $report_values['IglesiaId'], $report_values['agno_id'], $i, $at, $leader_id, $disc_id);
                $j++;
            }
            $data[] = $data_array;
        }
        $data[] = $categories;

        $res = array(
            "success" => true,
            "msg" => '',
            "data" => $data,
            "errors" => ''

          );
          $this->layout->printLike(json_encode($res), 'json');
          
      }
      
 public function leader_report() {
        //$user_id  = $this->input->post('userId');
        //$group_id = $this->input->post('group_id');
        $type = $this->input->post('type');
        $agno = $this->input->post('agno');
        $mi = $this->input->post('mi');
        $mf = $this->input->post('mf');
        $user_group = $this->input->post('users_group');

        $this->load->model("rols_model");
        $this->load->model("grupos_model");
        $this->load->model("tipogrupos_model");
        $this->load->model("tiporols_model");
        $this->load->model("users_model");

        $group_type = $this->tipogrupos_model->getByNameGrupo('celula');



        $group_type = $group_type[0]->TipoGrupoId;
        $encounter_type = $this->tipogrupos_model->getByNameGrupo('encuentro');

        // print_r($group_type);

        $encounter_type = $encounter_type[0]->TipoGrupoId;
        $role_id = $this->tiporols_model->getBynombrerol('lider');

        // print_r($role_id);

        $role_id = $role_id[0]->TipoRolId;

        $data = array();
        $total_array = array();
        $user_array = array();

        foreach ($user_group as $ug) {

            $ug = explode('_', $ug);
            $user_name = $this->users_model->getByUserId($ug[0]);
            $user_name = $user_name[0]->nombre1 . ' ' . $user_name[0]->apellido1;

            //  echo $user_name."-  ";

            $array_group = array();
            $array_group_global = array();
            $array_leader = array();

            $array_group[] = $ug[1];
            $array_leader[] = $ug[0];
            $array_group_global[] = $ug[1];
            $flag = true;
            while ($flag == true) {
                $id_grupo = $array_group[0];
                $uid = $array_leader[0];

                $members_data = $this->rols_model->getByGrupoId($id_grupo);

                //  print_r($members_data);
                //     echo "uid: ".$uid.", ";
                foreach ($members_data as $mb) {

                    //        print_r($members_data);
                    //VERIFICAR QUE LOS USUARIOS SEAN LIDERES DE UN GRUPO CELULA
                    if ($uid != $mb->UserId) {
                        $user_dat = $this->grupos_model->is_leader_group($mb->UserId, $group_type, $role_id);

                        //   print_r($user_dat);

                        if (!empty($user_dat)) {
                            $array_group[] = $user_dat->GrupoId;
                            $array_group_global[] = $user_dat->GrupoId;
                            $array_leader[] = $mb->UserId;
                            //echo "entro aqui , ";
                        }
                    }
                }
                //print_r($array_group);
                unset($array_group[0]);
                unset($array_leader[0]);
                $array_group = array_values($array_group);
                $array_leader = array_values($array_leader);

                //print_r($array_group);

                if (count($array_group) == 0)
                    $flag = false;
            }
            $list = "'" . implode("', '", $array_group_global) . "'";

            //       echo $list;

            switch ($type) {

                case 1:
                    $var = $this->grupos_model->get_users_cell_encounter($list, $encounter_type, $agno, $mi, $mf);
                    if ($var['success'] == true) {
                        //$data[] = array('username'=>$user_name,'total'=>$var['total']+0);
                        $total_array[] = $var['total'] + 0;
                        $user_array[] = $user_name;
                    }

                    break;

                case 2:
                    $var = $this->grupos_model->get_filter_cell($array_group_global, $agno, $mi, $mf);
                    if ($var['success'] == true) {
                        $total_array[] = $var['total'] + 0;
                        $user_array[] = $user_name;
                    }


                    break;

                case 3:
                    $var = $this->grupos_model->get_users_cell($list, $agno, $mi, $mf);
                    if ($var['success'] == true) {
                        //$data[] = array('username'=>$user_name,'total'=>$var['total']+0);
                        $total_array[] = $var['total'] + 0;
                        $user_array[] = $user_name;
                    }
                    break;
            }
        }
        $data[] = $total_array;
        $data[] = $user_array;

        $res = array(
            "success" => true,
            "msg" => '',
            "data" => $data,
            "errors" => ''
        );
        $this->layout->printLike(json_encode($res), 'json');
    }

    public function load_leader_cells() {
        $conditions = array();
        $page = $this->input->post("page");
        $rp = $this->input->post("rp");

        $sort = $this->input->post("sortname");
        $dir = $this->input->post("sortorder");

        $query = $this->input->post("query");
        $qtype = $this->input->post("qtype");

        //$id_iglesia = $this->input->post("item");
        //$id_iglesia = $this->input->post("IglesiaId");


        $conditions = array();
        if (!empty($query) && $query !== "null") {
            if ($qtype == 'ngrupo')
                array_push($conditions, array('field' => 'tbl_grupos.nombre', 'value' => $query, 'type' => 'like'));
            else if ($qtype == 'nombres')
                array_push($conditions, array('field' => 'tbl_users.nombre1', 'value' => $query, 'type' => 'like'));
            else if ($qtype == 'apellidos')
                array_push($conditions, array('field' => 'tbl_users.apellido1', 'value' => $query, 'type' => 'like'));
        }

        $this->load->model("tipogrupos_model");
        $this->load->model("tiporols_model");
        $this->load->model("grupos_model");
        $group_type = $this->tipogrupos_model->getBynombre('celula');
        $group_type = $group_type[0]->TipoGrupoId;
        $role_id = $this->tiporols_model->getBynombrerol('Lider');
        $role_id = $role_id[0]->TipoRolId;

        $order = null;
        if (!empty($sort) && $sort !== "null") {
            $obj = json_decode($sort);
            $order = array(
                "field" => $sort,
                "direction" => $dir
            );
        }

        $selected = array();
        $items = $this->grupos_model->load_leader_cells($page, $rp, $conditions, $order, $selected, $group_type, $role_id);
        $data = array(
            "success" => true,
            "total" => $items["results"],
            "rows" => $items["items"],
            "page" => $items["page"]
        );
        $this->layout->printLike(json_encode($data), "json");
    }

    function loadUsersTree_mas_otras_celulas() {
        $id = $this->input->post("id");
        $first = $this->input->post("first");
        
        $this->load->model('tiporols_model');
        $this->load->model('tipogrupos_model');
        $this->load->model('rols_model');
        $this->load->model('grupos_model');
        $this->load->model('users_model');
        
        $liderId = $this->tiporols_model->getBynombrerol('lider');
        $liderId = $liderId[0]->TipoRolId;
        
        $disipuloId = $this->tiporols_model->getBynombrerol('discipulo');
        $disipuloId = $disipuloId[0]->TipoRolId;
        
        $grupoId = $this->tipogrupos_model->getByNameGrupo('celula');
        $grupoId = $grupoId[0]->TipoGrupoId;
        
        $data = array();
        
        $rootUser = array();
        if (!empty($id) && intval($id) > 0):
            $rootUser = $this->users_model->getByUserId($id);
        else:
            $rootUser = $this->users_model->getByroot('S');
        endif;
        $rootUser = $rootUser[0];
        
        if (!empty($rootUser)):
            $roles = $this->rols_model->getMembersByLider($rootUser->UserId,$liderId, $grupoId); 
        
            $grupo = array();
            
            $gruposToLook = array();
            
            $discipulos = array();
            
            foreach ($roles as $rol):
                $grupo = $this->grupos_model->getByGrupoId($rol->GrupoId);
                if (!empty($grupo)){
                    $grupo = $grupo[0];
                    $gruposToLook[] = $grupo;
              //      break;
                }
            endforeach;
            $miembros = array();
//            if (!empty($grupo)) {
//                $miembros = $this->rols_model->getMemberByGroup($grupo->GrupoId, $grupoId);
//            }
            
            //print_r($gruposToLook);exit;
            
            foreach($gruposToLook as $groupItem) {
                $miembros = array_merge($this->rols_model->getMemberByGroup($groupItem->GrupoId, $grupoId),$miembros);
            }
            
            foreach ($miembros as $miembro):
                if($rootUser->UserId !== $miembro->UserId){
                    $tmp = $this->users_model->getByUserId($miembro->UserId);
                    $tmp = $tmp[0];
                    $discipulos[] = array(
                        "id" => $tmp->UserId,
                        "name" => $tmp->nombre1 . " " . $tmp->apellido1,
                        "data" => array(
                            "nombre" => $tmp->nombre1 . " " . $tmp->nombre2 . " " . $tmp->apellido1 . " " . $tmp->apellido2,
                            "email" => $tmp->email,
                            "fono_fijo" => $tmp->fono_fijo,
                            "fono_movil" => $tmp->fono_movil,
                            "direccion" => $tmp->direccion,
                            "avatar" =>$tmp->avatar
                        )
                    );
                }
            endforeach;
            $data = array(
                "id" => $rootUser->UserId,
                "name" => $rootUser->nombre1 . " " . $rootUser->apellido1,
                "children" => $discipulos
            );
        else:
            $data = "";
        endif;
        $this->layout->printLike(json_encode($data), 'json');
    }

    
      function loadUsersTree() {
        $id = $this->input->post("id");
        $first = $this->input->post("first");
        
        $this->load->model('tiporols_model');
        $this->load->model('tipogrupos_model');
        $this->load->model('rols_model');
        $this->load->model('grupos_model');
        $this->load->model('users_model');
        
        $liderId = $this->tiporols_model->getBynombrerol('lider');
        $liderId = $liderId[0]->TipoRolId;
        
        $disipuloId = $this->tiporols_model->getBynombrerol('discipulo');
        $disipuloId = $disipuloId[0]->TipoRolId;
        
        $grupoId = $this->tipogrupos_model->getByNameGrupo('celula');
        $grupoId = $grupoId[0]->TipoGrupoId;
        
        $data = array();
        
        $rootUser = array();
        if (!empty($id) && intval($id) > 0):
            $rootUser = $this->users_model->getByUserId($id);
        else:
            $rootUser = $this->users_model->getByroot('S');
        endif;
        $rootUser = $rootUser[0];
        
        if (!empty($rootUser)):
            $roles = $this->rols_model->getMembersByLider($rootUser->UserId,$liderId, $grupoId); 
        
            $grupo = array();
            
            $gruposToLook = array();
            
            $discipulos = array();
            
            foreach ($roles as $rol):
                $grupo = $this->grupos_model->getByGrupoId($rol->GrupoId);
                if (!empty($grupo)){
                    $grupo = $grupo[0];
                    $gruposToLook[] = $grupo;
              //      break;
                }
            endforeach;
            $miembros = array();
            if (!empty($grupo)) {
                $miembros = $this->rols_model->getMemberByGroup($grupo->GrupoId, $grupoId);
            }
            
            //print_r($gruposToLook);exit;
            
//            foreach($gruposToLook as $groupItem) {
//                $miembros = array_merge($this->rols_model->getMemberByGroup($groupItem->GrupoId, $grupoId),$miembros);
//            }
            
            foreach ($miembros as $miembro):
                if($rootUser->UserId !== $miembro->UserId){
                    $tmp = $this->users_model->getByUserId($miembro->UserId);
                    $tmp = $tmp[0];
                    $discipulos[] = array(
                        "id" => $tmp->UserId,
                        "name" => $tmp->nombre1 . " " . $tmp->apellido1,
                        "data" => array(
                            "nombre" => $tmp->nombre1 . " " . $tmp->nombre2 . " " . $tmp->apellido1 . " " . $tmp->apellido2,
                            "email" => $tmp->email,
                            "fono_fijo" => $tmp->fono_fijo,
                            "fono_movil" => $tmp->fono_movil,
                            "direccion" => $tmp->direccion,
                            "avatar" =>$tmp->avatar
                        )
                    );
                }
            endforeach;
            $data = array(
                "id" => $rootUser->UserId,
                "name" => $rootUser->nombre1 . " " . $rootUser->apellido1,
                "children" => $discipulos
            );
        else:
            $data = "";
        endif;
        $this->layout->printLike(json_encode($data), 'json');
    }
    
}

?>
